/*
 * Copyright (c) 2019 the Eclipse Milo Authors
 *
 * This program and the accompanying materials are made
 * available under the terms of the Eclipse Public License 2.0
 * which is available at https://www.eclipse.org/legal/epl-2.0/
 *
 * SPDX-License-Identifier: EPL-2.0
 */

package org.eclipse.milo.examples.client;

import java.util.List;
import java.util.concurrent.CompletableFuture;

import com.google.common.collect.ImmutableList;
import org.eclipse.milo.opcua.sdk.client.OpcUaClient;
import org.eclipse.milo.opcua.stack.core.types.builtin.DataValue;
import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;
import org.eclipse.milo.opcua.stack.core.types.builtin.StatusCode;
import org.eclipse.milo.opcua.stack.core.types.builtin.Variant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WriteExample implements ClientExample {

    public static void main(String[] args) throws Exception {
        WriteExample example = new WriteExample();

        new ClientExampleRunner(example).run();
    }

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void run(OpcUaClient client, CompletableFuture<OpcUaClient> future) throws Exception {
        // synchronous connect
        //消费者可以使用get方法来阻塞当前线程，直到get()结果。
        client.connect().get();


        //先设定一个node集合  ，NodeId 与 NodeId 之间用逗号隔开
        List<NodeId> nodeIds = ImmutableList.of(new NodeId(3, "Int32"),new NodeId(3, "String"));

        for (int i = 0; i < 10; i++) {
            Thread.sleep(1200);
            //注意 如果你要一次 写 多个变量，那么 Variant、DataValue 这些都不能共用 同一个，要分开
            Variant v = new Variant(i);
            Variant v2 = new Variant(String.valueOf(i));

            // don't write status or timestamps
            DataValue dv = new DataValue(v, null, null);
            DataValue dv2 = new DataValue(v2, null, null);

            List<DataValue> values = ImmutableList.of(dv,dv2);
            // write asynchronously....
            // 一次可以写 一个node 集合。
            CompletableFuture<List<StatusCode>> f =
                    //注意上面的nodeIds必须和ImmutableList.of(dv,dv)写的values 个数相互一致
                    client.writeValues(nodeIds, values);

            // ...but block for the results so we write in order,,
            // write 和read 都是异步异步的我们也可以调用get()方法来阻塞线程，等拿到结果。
            List<StatusCode> statusCodes = f.get();
            StatusCode status = statusCodes.get(0);
            StatusCode status2 = statusCodes.get(1);

            if (status.isGood() && status2.isGood()) {
                logger.info("Wrote '{}' to nodeId={}", v, nodeIds.get(0));
            }
        }

        future.complete(client);
    }


}
